<template>
  <div>
    <template>
      <div v-if="roleId.length > 0">
        <el-tree
          v-loading="treeLoading"
          :data="menuList"
          show-checkbox
          ref="tree"
          node-key="menuId"
          check-strictly
          :props="defaultProps"
        />
      </div>
      <div v-else>
        请选择角色
      </div>
    </template>
  </div>
</template>

<script>
import { getPageData } from '@/api/common/page'
import { saveRoleMenu, getMenusByRole } from '@/api/sys/role'
export default {
  name: 'roleMenu',
  props: ['roleId'],
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      menuList: [],
      treeLoading: true
    }
  },
  mounted() {
    getPageData('sys/menu/getMenuAll', {
      page: 1,
      limit: 10,
      info: '{"parentId":"0"}'
    }).then((res) => {
      this.menuList = res.obj.records
    })
  },
  watch: {
    async roleId(val) {
      this.treeLoading = true
      await getMenusByRole(val).then((res) => {
        this.$refs.tree.setCheckedKeys(res.obj.menus)
        this.treeLoading = false
      })
    }
  },
  methods: {
    async getRoleTreeKeys() {
      this.treeLoading = true
      const tree = this.$refs.tree
      const menuCheckNodes = tree.getCheckedKeys()
      await saveRoleMenu(this.roleId, menuCheckNodes).then((res) => {
        if (res.obj) {
          this.$message({
            message: '权限设置成功',
            type: 'success'
          })
        }
        this.treeLoading = false
      })
    }
  }
}
</script>
